<?php
namespace dgwht\sms;
use GuzzleHttp\Client as HttpClient;

class Tx {

	private $rand = '';
	private $time = '';
	private $Config;

	function __construct($config=[]) {
		//短信应用ID
        $this->Config['id'] = isset($config['id']) ? $config['id'] : '';
		//应用KEY
        $this->Config['key'] = isset($config['key']) ? $config['key'] : '';
		//签名
        $this->Config['sign'] = isset($config['sign']) ? $config['sign'] : '';
		//模板ID
        $this->Config['tpl'] = isset($config['tpl']) ? $config['tpl'] : '';
		$this->rand = rand( 1001, 9999 );
		$this->time = time();
	}
	
	public function send( $phone, $data ) {
		try{
			$url = $this->getUrl();
			$httpData = $this->getData($phone, $data);
			
            $httpClient = new HttpClient();
            $response = $httpClient->request('POST', $url, ['json' => $httpData]);
			$ret = $response->getBody()->getContents();
			
			$ret = json_decode( $ret, true );
		}catch(Exception $e) {
			return $e;
		}
		if(isset($ret[ "errmsg" ]) && $ret[ "errmsg" ] != 'OK'){
		    return $ret[ "errmsg" ];
		}
		if(isset($ret['ErrorInfo'])){
		    return $ret['ErrorInfo'];
		}
		return true;
	}

	private function getUrl(){
		$url = '?sdkappid=' . $this->Config['id'];
		$url .= '&random=' . $this->rand;
		$url = 'https://yun.tim.qq.com/v5/tlssmssvr/sendsms' . $url;
		return $url;
	}
	
	private function getData($phone='', $params=[]){
		$str = "appkey=" . $this->Config['key'];
		$str .="&random=" . $this->rand;
		$str .= "&time=" . $this->time;
		$str .= "&mobile=" . $phone;
		$data = array();
		$data[ 'sig' ] = $this->sha256($str);
		$data[ 'ext' ] = "";
		$data[ 'extend' ] = "";
		$data[ 'params' ] = $params;
		$data[ 'sign' ] = $this->Config['sign'];
		$data[ 'tel' ] = array( "mobile" => $phone, "nationcode" => "86" );
		$data[ 'time' ] = $this->time;
		$data[ 'tpl_id' ] = $this->Config['tpl'];
// 		$data = json_encode( $data, JSON_UNESCAPED_UNICODE );
		return $data;
	}
	
	private function sha256( $data, $rawOutput = false ) {
		if ( !is_scalar( $data ) ) {
			return false;
		}
		$data = ( string )$data;
		$rawOutput = !!$rawOutput;
		return hash( 'sha256', $data, $rawOutput );
	}

}